package com.njupt.sellsec.service.Impl;

import com.njupt.sellsec.domain.*;
import com.njupt.sellsec.redis.RedisService;
import com.njupt.sellsec.redis.SecSellKey;
import com.njupt.sellsec.service.GoodsService;
import com.njupt.sellsec.service.OrderService;
import com.njupt.sellsec.service.SecSellService;
import com.njupt.sellsec.vo.GoodsFormVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Random;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 17:15 2018/7/29
 * @Modified By:
 **/
@Service
public class SecSellServiceImpl implements SecSellService {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisService redisService;

    @Transactional
    @Override
    public OrderInfo secSell(SellUser user, GoodsFormVO goods) {

        //减库存
        boolean result = goodsService.decreaseStock(goods.getId());
        if (result){
            //下订单
            OrderInfo orderInfo = orderService.createOrder(user,goods);
            //写入秒杀订单
            return orderInfo;
        }else {
            setGoodsOver(goods.getId());
            return null;
        }
    }


    @Override
    public long getSecSellResult(long userId,long goodsId) {
           SecOrder secOrder = orderService.getSecOrderByUserIdAndGoodsId(userId,goodsId);
           if (secOrder!=null){
               return secOrder.getOrderId();
           }else{
              boolean isOver = getGoodsOver(goodsId);
              if (isOver){
                  return -1;
              }else {
                  return 0;
              }
           }
    }

    @Override
    public void reset(List<GoodsFormVO> goodsFormVOList) {
        goodsService.resetStock(goodsFormVOList);
        orderService.deleteOrders();
    }

    @Override
    public boolean check(String path, SellUser user, long goodsId) {
        if (path==null||user==null){
            return false;
        }
        String result = redisService.get(SecSellKey.getSecSellPath,""+user.getId()+""+goodsId,String.class);
        return path.equals(result);
    }

    @Override
    public BufferedImage createVerifyCode(SellUser user, long goodsId) {

        if(user == null || goodsId <=0) {
            return null;
        }
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        // create a random instance to generate the codes
        Random rdm = new Random();
        // make some confusion
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        // generate a random code
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        //把验证码存到redis中
        int rnd = calc(verifyCode);
        redisService.set(SecSellKey.getSecSellVerifyCode, user.getId()+","+goodsId, rnd);
        //输出图片
        return image;

    }

    /**
     * 验证验证码
     * @param user
     * @param goodsId
     * @param verifyCode
     * @return
     */
    @Override
    public boolean checkVerifyCode(SellUser user, long goodsId, int verifyCode) {
        if (user==null||goodsId<=0){
            return false;
        }
       Integer result = redisService.get(SecSellKey.getSecSellVerifyCode, user.getId()+","+goodsId,Integer.class);
        if (result==null||result-verifyCode!=0){
            return false;
        }
        //删除验证过的验证码
        redisService.del(SecSellKey.getSecSellVerifyCode, user.getId()+","+goodsId);
        return true;
    }

    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer)engine.eval(exp);
        }catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private static char[] ops = new char[] {'+', '-', '*'};
    /**
     * + - *
     * */
    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = ""+ num1 + op1 + num2 + op2 + num3;
        return exp;
    }

    /**
     * 判断缓存中的商品是否秒杀完
     *
     * @param goodsId
     * @return
     */
    private boolean getGoodsOver(long goodsId) {
        return redisService.exits(SecSellKey.isGoodsOver,""+goodsId);

    }

    /**
     * 设置秒杀完的商品到缓存
     * @param id
     */
    private void setGoodsOver(Long id) {
        redisService.set(SecSellKey.isGoodsOver,""+id,true);

    }
}
